package com.hong.shiro;

import com.hong.domain.User;
import com.hong.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Auther: csh
 * @Date: 2019/11/6 11:45
 * @Description:
 */
public class UserRealm extends AuthorizingRealm {


    @Autowired
    private UserService userService;

    /**
     *
     * 功能描述:执行授权逻辑
     *
     * @param:
     * @return:
     * @auther: csh
     * @date: 2019/11/6 11:46
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行授权逻辑");

        //给资源进行授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前登录用户
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        //给资源的授权字符串
        info.addStringPermission(user.getPerms());
        return info;
    }
    /**
     *
     * 功能描述:执行认证逻辑
     *
     * @param:
     * @return:
     * @auther: csh
     * @date: 2019/11/6 11:46
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行认证逻辑");
        //1判断用户名
        UsernamePasswordToken token1 = (UsernamePasswordToken)token;

        User user = userService.findByUserName(token1.getUsername());

        if(null==user){
            //用户名不存在
            return null;
        }
        //2.判断密码
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
